// 模拟WebSocket服务，用于开发和测试
export class MockWebSocketService {
  private listeners: Map<string, Set<(data: any) => void>> = new Map()
  private timers: Map<string, number> = new Map()
  private isActive = false

  start() {
    if (this.isActive) return
    this.isActive = true

    // 模拟系统指标推送
    this.timers.set('system_metrics', window.setInterval(() => {
      this.emit('system_metrics', this.generateSystemMetrics())
    }, 5000))

    // 模拟生命体指标推送
    this.timers.set('life_entity_metrics', window.setInterval(() => {
      this.emit('life_entity_metrics', this.generateLifeEntityMetrics())
    }, 10000))

    // 模拟活动更新
    this.timers.set('activity_update', window.setInterval(() => {
      this.emit('activity_update', this.generateActivityUpdate())
    }, 15000))

    // 模拟告警
    this.timers.set('alert', window.setInterval(() => {
      if (Math.random() < 0.3) {
        this.emit('alert', this.generateAlert())
      }
    }, 30000))

    // 模拟健康状态变化
    this.timers.set('health_change', window.setInterval(() => {
      if (Math.random() < 0.4) {
        this.emit('health_change', this.generateHealthChange())
      }
    }, 20000))

    console.log('Mock WebSocket service started')
  }

  stop() {
    this.isActive = false
    this.timers.forEach((timer) => {
      clearInterval(timer)
    })
    this.timers.clear()
    console.log('Mock WebSocket service stopped')
  }

  subscribe(type: string, callback: (data: any) => void): () => void {
    if (!this.listeners.has(type)) {
      this.listeners.set(type, new Set())
    }
    
    this.listeners.get(type)!.add(callback)

    return () => {
      const callbacks = this.listeners.get(type)
      if (callbacks) {
        callbacks.delete(callback)
        if (callbacks.size === 0) {
          this.listeners.delete(type)
        }
      }
    }
  }

  private emit(type: string, data: any) {
    const callbacks = this.listeners.get(type)
    if (callbacks) {
      callbacks.forEach(callback => {
        try {
          callback(data)
        } catch (error) {
          console.error('Mock WebSocket callback error:', error)
        }
      })
    }
  }

  private generateSystemMetrics() {
    return {
      cpuUsage: 30 + Math.floor(Math.random() * 50),
      memoryUsage: 40 + Math.floor(Math.random() * 40),
      networkLatency: 50 + Math.floor(Math.random() * 150),
      activeConnections: 200 + Math.floor(Math.random() * 300),
    }
  }

  private generateLifeEntityMetrics() {
    return {
      totalCount: 1200 + Math.floor(Math.random() * 100),
      activeCount: 800 + Math.floor(Math.random() * 200),
      newToday: Math.floor(Math.random() * 50),
      avgHealthScore: 60 + Math.random() * 30,
      networkConnections: 3000 + Math.floor(Math.random() * 1000),
      networkDensity: 0.5 + Math.random() * 0.3,
    }
  }

  private generateActivityUpdate() {
    const entityNames = ['智能制造公司', '深圳市', '创新概念', '混合实体001', '北京市', 'AI概念']
    const activityTypes = ['状态更新', '关系建立', '进化', '融合', '交互']
    const entityTypes = ['corporate', 'urban', 'conceptual', 'hybrid']
    const descriptions = [
      '意识等级提升到高级', '与其他实体建立协作关系', '概念结构发生变异',
      '完成多实体融合过程', '与系统进行深度交互', '网络连接优化完成'
    ]

    return {
      entityName: entityNames[Math.floor(Math.random() * entityNames.length)],
      type: activityTypes[Math.floor(Math.random() * activityTypes.length)],
      description: descriptions[Math.floor(Math.random() * descriptions.length)],
      entityType: entityTypes[Math.floor(Math.random() * entityTypes.length)],
      healthScore: 60 + Math.floor(Math.random() * 40),
    }
  }

  private generateAlert() {
    const levels = ['info', 'warning', 'error']
    const messages = [
      '系统性能优化完成', 'CPU使用率持续偏高', '生命体连接异常',
      '网络延迟增加', '新生命体创建成功', '健康度监控异常'
    ]
    const descriptions = [
      '系统性能已优化，响应速度提升20%', '系统CPU使用率在过去30分钟内持续超过80%',
      '检测到3个生命体失去网络连接', '网络延迟超过正常范围，建议检查网络状态',
      '成功创建了5个新的企业生命体', '部分生命体健康度监控出现异常'
    ]

    const index = Math.floor(Math.random() * messages.length)
    return {
      level: levels[Math.floor(Math.random() * levels.length)],
      message: messages[index],
      description: descriptions[index],
    }
  }

  private generateHealthChange() {
    const entityNames = ['智能制造公司', '深圳市', '创新概念', '混合实体001']
    const changes = ['improve', 'decline', 'stable']

    const oldScore = 50 + Math.floor(Math.random() * 40)
    const change = Math.floor(Math.random() * 21) - 10
    const newScore = Math.max(10, Math.min(100, oldScore + change))

    return {
      entityName: entityNames[Math.floor(Math.random() * entityNames.length)],
      oldScore,
      newScore,
      change: change > 5 ? 'improve' : change < -5 ? 'decline' : 'stable',
    }
  }
}

// 创建全局实例
export const mockWebSocketService = new MockWebSocketService()